package com.hunlian.makelove.update;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hunlian.makelove.R;

import java.io.File;


public class Update {

	private Context context;
	private Activity activity;
	private ProgressDialog mProgressDialog;
	private String mLocalVersion;
	private AppDownloadManager mAppDownloadManager;
	// 更新
	private TextView loaded_percent, loaded_size, total_size;
	private Button btnBackgroundUpdate, btnCancel;
	private ProgressBar progressHorizontalDownload;
	// 更新升级的广播接收器
	private MyBorderReceiver receiver;
	/**
	 * 是否正在下载的标志位
	 */
	private boolean isDownloading = false;
	/**
	 * 软件升级对话框
	 */
	private AlertDialog dialog;
	/**
	 * 下载地址
	 */
	private String url;
	/**
	 * 是否有新版本接口
	 */
	private HasNewVersionListener hasNewVersionListener;
	/**
	 * 下载完成回调接口
	 */
	private DownloadOverListener downloadOverListener;

	/**
	 * 检查更新的结果
	 */
	private AppUpdate appUpdate;
	/**
	 * 下载中接收广播接口
	 */
	private DownloadingReceiverListener downloadingReceiverListener;
	/**
	 * 取消下载接口
	 */
	private CancelDownloadListener cancelDownloadListener;
	
	//判断是否有大版本更新
	private boolean mbigVersion = false;
	private LinearLayout ll_control;
	private String apkName;
	public void checkUpdate(Activity activity) {
		context = activity;
		this.activity = activity;
		/*AppUpdateTask task = new AppUpdateTask(activity);
		task.execute();*/
		isDownloading = false;

		// 注册广播接收器
		registerReceiver();

	}
	public void setUpdate(AppUpdate appUpdatge){
		this.appUpdate = appUpdatge;
		if(!appUpdatge.getType().equals("1")){
			mbigVersion = true;
		}
	}

	/** 检查升级任务 */
	public class AppUpdateTask extends
			AsyncTask<Void, WebServiceError, AppUpdate> {

		private Activity mActivity;

		public AppUpdateTask(Activity mActivity) {
			super();
			this.mActivity = mActivity;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// startProgress();
		}

		@Override
		protected AppUpdate doInBackground(Void... params) {
			//TourHttpApi service = new TourHttpApi();
			AppUpdate appUpdate = null;
			/*try {
				//appUpdate = service.queryAppUpdate();
			} catch (WebServiceError e) {
				e.printStackTrace();
				publishProgress(e);
			}*/
			return appUpdate;
		}

		@Override
		protected void onPostExecute(AppUpdate result) {
			super.onPostExecute(result);
			stopProgress();
			if (result == null) {
				Toast.makeText(mActivity, "网络错误，请稍后再试！", Toast.LENGTH_SHORT)
						.show();
				return;
			}
			appUpdate = result;
			if (hasNewVersionListener != null) {
				boolean hasNewVersion = isNeedShowDialog(result.getVersion());
				hasNewVersionListener.hasNewVersion(hasNewVersion);
			}

		}

		@Override
		protected void onProgressUpdate(WebServiceError... values) {
			Toast.makeText(mActivity, values[0].getMessage(),
					Toast.LENGTH_SHORT).show();
			super.onProgressUpdate(values);
		}

		@Override
		protected void onCancelled() {
			// stopProgress();
			super.onCancelled();
		}

	}

	protected void startProgress() {
		if (mProgressDialog == null) {
			mProgressDialog = new ProgressDialog(activity);
			mProgressDialog.setMessage("正在检测版本号，请稍等...");
		}
		mProgressDialog.show();
	}

	protected void stopProgress() {
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
			mProgressDialog = null;
		}
	}

	public boolean isNeedShowDialog(String remoteVersion) {
		mLocalVersion = getVersionName(context);
		// 本地版本号转成float类型
		String[] localStrings = mLocalVersion.split("\\.");
		String localString = localStrings[0] + "." + localStrings[1];
		float flocal = Float.parseFloat(localString);
		// 服务器版本号转成float类型
		String[] remoteStrings = remoteVersion.split("\\.");
		String remoteString = remoteStrings[0] + "." + remoteStrings[1];
		float fremote = Float.parseFloat(remoteString);
		// 当前版本号小于服务器版本号
		if (flocal < fremote) {
		    float fstLocal = Float.parseFloat(localStrings[0]);
		    float fstRemote = Float.parseFloat(remoteStrings[0]);
		    if (fstLocal < fstRemote) {			
				mbigVersion = true;
		    }
		    return true;
		}
		// 如果前两个版本号相等，则判断第三个版本号
		if (flocal == fremote) {
			return Integer.parseInt(remoteStrings[2]) > Integer
					.parseInt(localStrings[2]);
		}
		return false;
	}

	public String getVersionName(Context context) {
		PackageInfo packageInfo = null;
		try {
			packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(),
							PackageManager.GET_CONFIGURATIONS);
		} catch (NameNotFoundException ex) {
			ex.printStackTrace();
		}

		return packageInfo == null ? "1.0.0" : packageInfo.versionName;
	}

	public void showUpdateDialog() {
		if (appUpdate == null) {
			Toast.makeText(activity, "你还没检查更新呢", Toast.LENGTH_SHORT).show();
			return;
		}
		dialog = new AlertDialog.Builder(activity).create();
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);

		View view = activity.getLayoutInflater().inflate(
				R.layout.dialog_check_version, null);
		dialog.setView(view);
		try {
			dialog.show();
		} catch (Exception e) {
		}

		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
		lp.width = (int) (dm.widthPixels * 0.86); // 设置宽度
		Window window = dialog.getWindow();
		window.setContentView(R.layout.dialog_check_version);
		window.setAttributes(lp);

		final LinearLayout llControlContent = (LinearLayout) window
				.findViewById(R.id.ll_control_content);

		Button cancelButton = (Button) window.findViewById(R.id.btn_cancel);
		ImageView lineImageView = (ImageView) window.findViewById(R.id.img_line);
		if (mbigVersion) {
		    cancelButton.setVisibility(View.GONE);
		    lineImageView.setVisibility(View.GONE);
		}
		TextView remoteVersion = (TextView) window
				.findViewById(R.id.tv_remote_version);
		remoteVersion.setText(appUpdate.getVersion());

		TextView updateContent = (TextView) window
				.findViewById(R.id.update_content);
		String content = appUpdate.getLog();

		if (content != null && content.length() > 0) {
			String[] log = content.split(";");
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < log.length; i++) {
				sb.append(log[i] + "\n");
			}

			updateContent.setText(sb.substring(0, sb.length() - 1));
		}

		cancelButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		Button sureButton = (Button) window.findViewById(R.id.btn_sure);
		sureButton.setOnClickListener(new OnClickListener() {

			
			@Override
			public void onClick(View v) {

				//registerReceiver();

				View view = activity.getLayoutInflater().inflate(
						R.layout.setting_download_view, null);
				mAppDownloadManager = new AppDownloadManager(activity);
				loaded_percent = (TextView) view
						.findViewById(R.id.loaded_percent);
				loaded_size = (TextView) view.findViewById(R.id.loaded_size);
				total_size = (TextView) view.findViewById(R.id.total_size);
				ll_control = (LinearLayout) view.findViewById(R.id.ll_control);
				if(mbigVersion){
					ll_control.setVisibility(View.GONE);
				}
				btnBackgroundUpdate = (Button) view
						.findViewById(R.id.btn_background_update);
				btnCancel = (Button) view.findViewById(R.id.btn_cancel);

				progressHorizontalDownload = (ProgressBar) view
						.findViewById(R.id.progress_horizontal_download);

				llControlContent.removeAllViews();
				llControlContent.addView(view);
				//System.out.println("isDownloading:"+isDownloading);
				apkName = activity.getString(R.string.app_name)
						+"_"+ appUpdate.getVersion() + ".apk";
				if (!isDownloading) {
					url = appUpdate.getDownloadUrl();
					mAppDownloadManager.startDownload(url, apkName);
				}
				/*
				 * dialog.dismiss();
				 * mAppDownloadManager.startDownload(appUpdate.
				 * getDownloadUrl());
				 */

				btnBackgroundUpdate.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
						// activity.unregisterReceiver(receiver);
						mAppDownloadManager.showNotification();

					}

				});

				btnCancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						mAppDownloadManager.stopDownload();
						// 将正在下载状态改为关闭
						isDownloading = false;
						
						try {
							activity.unregisterReceiver(receiver);
							clearNotification();
						} catch (Exception e) {
							Toast.makeText(activity, e.getMessage(), Toast.LENGTH_SHORT).show();
						}
						dialog.dismiss();

						if (cancelDownloadListener != null) {
							cancelDownloadListener.cancelDownload();
						}

					}

				});

			}
		});

		//System.out.println("--判断更新状态-isDownloading-------" + isDownloading);
		// 如果当前正在下载状态
		if (isDownloading) {
			sureButton.performClick();
		}
	}

	private void registerReceiver() {
		// 初始化广播接收器
		receiver = new MyBorderReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(activity.getPackageName());
		context.registerReceiver(receiver, filter);
	}

	public class MyBorderReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			if (downloadingReceiverListener != null) {
				downloadingReceiverListener.downloadingReceiver(intent);
			}

			String error = intent.getStringExtra("error");
			if (error.equals("")) {
				isDownloading = true;
			} else {
				isDownloading = false;
				dialog.dismiss();

				/*
				 * if(tvVersion!=null) tvVersion.setText("有新版本");
				 */
				Toast.makeText(activity, error, Toast.LENGTH_SHORT).show();
			}

			int curPercent = intent.getIntExtra("curPercent", 0);
			String curSize = intent.getStringExtra("curSize");
			String totalSize = intent.getStringExtra("totalSize");
			boolean isDelay = intent.getBooleanExtra("delay", false);
			if (loaded_percent == null)
				return;
			loaded_percent.setText(curPercent + "%");
			loaded_size.setText(curSize);
			total_size.setText(totalSize);

			progressHorizontalDownload.setProgress(curPercent);
			// 更新完成
			if (curPercent == 100) {
				if(!mbigVersion){
					if(isDelay){
						Handler handler = new Handler();  
				        //使用pastDelayed方法延时  
				        handler.postDelayed(new Runnable() {  
				  
				            @Override  
				            public void run() {  
								// 取消对话框
								if ((activity != null) && dialog != null && dialog.isShowing()) {
									dialog.dismiss();
								}
								if (downloadOverListener != null) {
									downloadOverListener.downloadOver();
								}
								//System.out.println("---更新完成-------");
								isDownloading = false;
				            }  
				        }, 500); 
					}else{
						// 取消对话框
						if ((activity != null) && dialog != null && dialog.isShowing()) {
							dialog.dismiss();
						}
						if (downloadOverListener != null) {
							downloadOverListener.downloadOver();
						}
						//System.out.println("---更新完成-------");
						isDownloading = false;
					}
				}else{
					//System.out.println("update完成");
					ll_control.setVisibility(View.VISIBLE);
					btnCancel.setVisibility(View.GONE);
					btnBackgroundUpdate.setText("安装");
					btnBackgroundUpdate.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							File fileDir = new File(Environment.getExternalStorageDirectory(), "izichan");
							File apkFile = new File(fileDir, apkName);
							installApkFile(apkFile);
						}
					});
				}
			}

		}

	}

	/**
	 * 是否有新版本接口
	 * 
	 * @author zealjiang
	 * @time 2014-6-10下午3:18:20
	 */
	public interface HasNewVersionListener {
		/**
		 * 是否有新版本;hasNewVersion为true表示有新版本，false表示没有新版本
		 * 
		 * @param hasNewVersion
		 */
		public void hasNewVersion(boolean hasNewVersion);
	}

	/**
	 * 设置AgencyStreetviewRotateOver监听器
	 *
	 */
	public void setHasNewVersionListener(
			HasNewVersionListener hasNewVersionListener) {
		this.hasNewVersionListener = hasNewVersionListener;
	}

	/**
	 * 是否有新版本接口
	 * 
	 * @author zealjiang
	 * @time 2014-6-10下午3:18:20
	 */
	public interface DownloadOverListener {
		/**
		 * 是否有新版本;hasNewVersion为true表示有新版本，false表示没有新版本
		 *
		 */
		public void downloadOver();
	}

	/**
	 * 设置AgencyStreetviewRotateOver监听器
	 *
	 */
	public void setDownloadOverListener(
			DownloadOverListener downloadOverListener) {
		this.downloadOverListener = downloadOverListener;
	}

	/**
	 * 正在更新接口
	 * 
	 * @author zealjiang
	 * @time 2014-6-10下午3:18:20
	 */
	public interface DownloadingReceiverListener {
		/**
		 * 正在更新接口;intent中的参数为String error,int curPercent,String curSize,String
		 * totalSize
		 * 
		 * @param intent
		 */
		public void downloadingReceiver(Intent intent);

	}

	/**
	 * 设置AgencyStreetviewRotateOver监听器
	 *
	 */
	public void setDownloadingReceiverListener(
			DownloadingReceiverListener downloadingReceiverListener) {
		this.downloadingReceiverListener = downloadingReceiverListener;
	}

	/**
	 * 正在更新接口
	 * 
	 * @author zealjiang
	 * @time 2014-6-10下午3:18:20
	 */
	public interface CancelDownloadListener {
		/**
		 * 正在更新接口;intent中的参数为String error,int curPercent,String curSize,String
		 * totalSize
		 *
		 */
		public void cancelDownload();

	}

	/**
	 * 设置AgencyStreetviewRotateOver监听器
	 *
	 */
	public void setCancelDownloadListener(
			CancelDownloadListener cancelDownloadListener) {
		this.cancelDownloadListener = cancelDownloadListener;
	}

	/**
	 * 解除注册的广播接收器，解除绑定的服务
	 */ 
	public void destroy() {
		try {
			context.unregisterReceiver(receiver);
			if(AppDownloadIntentService.canDownload){
				mAppDownloadManager.unboundService();
				mAppDownloadManager = null;
			}

			if ((activity != null) && dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			
		} catch (Exception e) {

		}
	}

	public void clearNotification() {
		if (mAppDownloadManager == null)
			return;
		mAppDownloadManager.clearNotification();
	}
	
	/** 安装apk */
	public void installApkFile(File file) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		context.startActivity(intent);
	}

}
